package com.insigma.yanwenlong.bookkeeping.db.jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBConnection {
	private  static String driver;
	private  static String url;
	private  static String user;
	private  static String password;
	private final static String path = DBConnection.class.getResource("").getPath() + "/db.properties"; 
	
	//创建数据库连接
	public static Connection getConnection() {
		loadProperties(path);
		Connection connection = null;
		try {
			//加载驱动
			Class.forName(driver);
			connection = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	private static void loadProperties(String propertiesPath) {
		Properties p = new Properties();
		try {
			p.load(new FileInputStream(propertiesPath));
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			user = p.getProperty("user");
			password = p.getProperty("password");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//关闭连接
	public static void closeConnection(Connection connection) {
		try {
			if(connection != null || !connection.isClosed()) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//关闭命令
	public static void closeStatement(Statement statement) {
		try {
			if(statement != null || !statement.isClosed()) {
				statement.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//关闭结果集
	public static void closeResultSet(ResultSet resultSet) {
		try {
			if(resultSet != null || !resultSet.isClosed()) {
				resultSet.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
